﻿Imports Cdm.DataCore.Admin
Imports System.Collections.Generic

Partial Class AdHocReport_AuditSearch
    Inherits System.Web.UI.Page

    Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SearchButton.Click
        BindGrids()
    End Sub

    Private Sub BindGrids()
        Dim auditList As List(Of Audit) = GetAuditResults()
        If auditList.Count > 0 Then
            BindDetailsColumns(auditList(0))
            ExportButton.Visible = True
        End If

        Me.AuditDetailsScrollingGridView.DataSource = auditList
        Me.AuditDetailsScrollingGridView.DataBind()
        Me.IdentifierGridView.DataSource = auditList
        Me.IdentifierGridView.DataBind()
        SetDetailColumnWidths()
    End Sub

    Private Function GetAuditResults() As List(Of Audit)
        Dim tableName As String = TableNameDropDown.SelectedValue
        Dim startDate As DateTime = New DateTime(1900, 1, 1)
        Dim endDate As DateTime = DateAdd(DateInterval.Day, 1, Now)

        If IsDate(StartDateTextBox.Text) Then
            startDate = CDate(StartDateTextBox.Text)
        End If

        If IsDate(EndDateTextBox.Text) Then
            endDate = CDate(EndDateTextBox.Text)
        End If

        Dim auditList As List(Of Audit) = Audit.AuditSearch(tableName, "", 0, startDate, endDate)
        Return auditList
    End Function

    Private Sub BindDetailsColumns(ByVal firstAudit As Audit)

        For iCol As Integer = 1 To firstAudit.NumberOfFields
            Dim colField As New BoundField
            Dim oldValField As New BoundField
            Dim newValField As New BoundField

            Dim colFieldName As String = String.Concat("Column", iCol.ToString())
            Dim oldValue As String = String.Concat("OldValue", iCol.ToString())
            Dim newValue As String = String.Concat("NewValue", iCol.ToString())

            colField.HeaderText = colFieldName
            colField.DataField = colFieldName
            oldValField.HeaderText = oldValue
            oldValField.DataField = oldValue
            newValField.HeaderText = newValue
            newValField.DataField = newValue

            newValField.HeaderStyle.Width = 80
            newValField.ItemStyle.Width = 80
            oldValField.HeaderStyle.Width = 80
            oldValField.ItemStyle.Width = 80
            colField.ItemStyle.Width = 80
            colField.HeaderStyle.Width = 80

            Me.AuditDetailsScrollingGridView.Columns.Add(colField)
            Me.AuditDetailsScrollingGridView.Columns.Add(oldValField)
            Me.AuditDetailsScrollingGridView.Columns.Add(newValField)
        Next

        Dim scrollScript As String
        scrollScript = String.Format("alignDivs('{0}', '{1}', '{2}');", _
                                   AuditDetailsScrollingGridView.DivClientId, _
                                   IdentifierGridView.DivClientId, _
                                   AuditDetailsScrollingGridView.HeaderDivClientId)
        AuditDetailsScrollingGridView.OnScrollJavaScript = scrollScript



    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetupJavascript()
    End Sub

    Private Sub SetupJavaScript()
        EntityController.JavaScriptAddChildDiv(Me.AuditDetailsScrollingGridView.DivClientId, CInt(Me.AuditDetailsScrollingGridView.ToolTip))
        EntityController.JavaScriptAddChildDiv(Me.IdentifierGridView.DivClientId, CInt(Me.IdentifierGridView.ToolTip))
        EntityController.JavaScriptSetFixedHeight(10)
    End Sub

    Private Sub SetDetailColumnWidths()
        Dim maxLength As Integer
        Dim currentLength As Integer
        For iCol As Integer = 0 To Me.AuditDetailsScrollingGridView.Columns.Count - 1
            maxLength = 8 * AuditDetailsScrollingGridView.Columns(iCol).HeaderText.Length

            For iRow As Integer = 0 To Me.AuditDetailsScrollingGridView.Rows.Count - 1
                currentLength = AuditDetailsScrollingGridView.Rows(iRow).Cells(iCol).Text.Length * 6
                If currentLength > maxLength Then maxLength = currentLength
                If iCol = 0 Then
                    For iCheck As Integer = 0 To 29
                        SetBold(iRow, 3 * iCheck, 3 * iCheck + 1, 3 * iCheck + 2)
                    Next
                    
                End If
            Next

            Me.AuditDetailsScrollingGridView.Columns(iCol).ItemStyle.Width = CStr(maxLength) + 10
            Me.AuditDetailsScrollingGridView.Columns(iCol).HeaderStyle.Width = CStr(maxLength) + 10
        Next

        Dim lastCol As Integer = Me.AuditDetailsScrollingGridView.Columns.Count - 1
        If lastCol >= 0 Then
            Me.AuditDetailsScrollingGridView.Columns(lastCol).HeaderStyle.Width = _
            Me.AuditDetailsScrollingGridView.Columns(lastCol).ItemStyle.Width.Value + 40
        End If
    End Sub

    Private Sub SetBold(ByVal irow As Integer, ByVal nameColumn As Integer, ByVal oldValColumn As Integer, ByVal newValColumn As Integer)
        If AuditDetailsScrollingGridView.Columns.Count <= newValColumn Then Exit Sub
        Dim oldValue As String = AuditDetailsScrollingGridView.Rows(irow).Cells(oldValColumn).Text
        Dim newValue As String = AuditDetailsScrollingGridView.Rows(irow).Cells(newValColumn).Text
        If oldValue <> newValue Then
            AuditDetailsScrollingGridView.Rows(irow).Cells(oldValColumn).Font.Bold = True
            AuditDetailsScrollingGridView.Rows(irow).Cells(newValColumn).Font.Bold = True
            AuditDetailsScrollingGridView.Rows(irow).Cells(nameColumn).Font.Bold = True
        End If
    End Sub

    Protected Sub ExportButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExportButton.Click
        Dim fileName As String = ""

        Try

            Dim directory As String = Server.MapPath(EntityController.FullPath(ConfigurationManager.AppSettings("ParticipantDocumentLocation")))
            If (Not directory.EndsWith("\")) Then
                directory = String.Concat(directory, "\")
            End If

            fileName = String.Concat(directory, "AuditLog", UserAuthorization.CurrentUser.LogonId, ".xls")


        Catch ex As Exception
            Response.Write("Error Getting File: " + ex.Message)
        End Try

        CreateExport(fileName)
    End Sub

    Private Sub CreateExport(ByVal fileName As String)

        Dim auditResults As List(Of Audit) = GetAuditResults()

        Dim criteria As New ArrayList()
        criteria.Add("Table Name: " + Me.TableNameDropDown.SelectedValue)
        If Not (String.IsNullOrEmpty(StartDateTextBox.Text)) Or _
               Not String.IsNullOrEmpty(EndDateTextBox.Text) Then
            criteria.Add("Date Range: " + StartDateTextBox.Text + " to " + EndDateTextBox.Text)
        End If

        'TODO (DH) - put the resuls in an Excel spreadsheet
        Dim exporter As New Spreadsheet.AdHocExport()
        exporter.ExportAuditLog(criteria, auditResults, fileName)

        Response.ContentType = "application/vnd.ms-excel"
        'Response.AppendHeader("Content-Disposition", "filename=Data.xlsx;");
        Response.AddHeader("Content-Disposition", "attachment;filename=AuditLog.xls")
        Response.AddHeader("Target", "_blank")
        Response.WriteFile(fileName)
        Response.Flush()
        System.IO.File.Delete(fileName)
        Response.End()
    End Sub

    Protected Sub IdentifierGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles IdentifierGridView.RowCommand
        If e.CommandName = "Details" Then
            Dim tableName As String = Me.TableNameDropDown.SelectedValue
            Dim id As Integer = CInt(e.CommandArgument)
            Dim details As String = Cdm.DataCore.Custom.SingleReturnValue.AuditDescription(id, tableName)
            PopupMessage1.ShowErrorMessage("Audit Details", details)
        End If
    End Sub
End Class
